package cn.ilikes.tools.nosql.jpa.classloads;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;

import cn.ilikes.tools.logs.Loggerfactory;
import cn.ilikes.tools.nosql.jpa.AbJPASQLPersistenceProvider;
import cn.ilikes.tools.nosql.jpa.classloads.URLPathLoadResources.ResourcesType;

public class JPASQLClassLoader extends ABJPASQLClassLoader implements IJPASQLClassLoader {

	private Logger logger = Loggerfactory.instance(AbJPASQLPersistenceProvider.class);

	private Map<String, byte[]> resources = new HashMap<String, byte[]>();

	class ClassPathFilter implements ClassFilter {

		private JPASQLClassLoader hbaseClassLoader;

		protected ClassPathFilter(JPASQLClassLoader hbaseClassLoader) {
			super();
			this.hbaseClassLoader = hbaseClassLoader;
		}

		@Override
		public boolean isFilter(String resourcesName, ResourcesType resourcesType) {
			if (resourcesType.equals(ResourcesType.classes))
				return true;
			else
				return false;
		}

		@Override
		public void filter(String resourcesName, byte[] resources) {

			Class clazz = hbaseClassLoader.findLoadedClass(resourcesName);

			if (clazz == null) {

				hbaseClassLoader.getResources().put(resourcesName, resources);
			}

			//				hbaseClassLoader.getResources().put(resourcesName, resources);
		}

	}

	private LoadResources loadResources = new URLPathFilterLoadResources(new ClassPathFilter(this));

	public JPASQLClassLoader(ClassLoader parentClassLoader) {
		super(parentClassLoader);

	}

	public JPASQLClassLoader() {
		super();

	}

	protected Map<String, byte[]> getResources() {
		return resources;
	}

	@Override
	public void loadResources(URL url) {

		loadResources.loadResource(url);
	}

	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		//		if(Loggerfactory.isdebug(logger))Loggerfactory.debug(logger, " findClass  "+name);
		Class<?> clazz = findLoadedClass(name);
		if (clazz != null)
			return clazz;

		byte[] con = resources.get(name);
		//		p(resources);
		if (con == null)
			throw new ClassNotFoundException("not find : " + name);
		clazz = defineClass(name, con, 0, con.length);
		return clazz;

	}

	@Override
	public Class<?> loadClass(String name) throws ClassNotFoundException {
		try {
			//		if(Loggerfactory.isdebug(logger))Loggerfactory.debug(logger, " loadClass "+name);
			if (name.endsWith("class"))
				name = name.substring(0, name.lastIndexOf(".class"));
			return super.loadClass(name);
		} catch (NoClassDefFoundError e) {
			throw new ClassNotFoundException(e.getMessage(), e);
		}
	}

}
